package com.jpush.library.utils;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.xindaoapp.happypet.ui.MainActivity;
import com.xindaoapp.happypet.ui.MessageCenterActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;

/**
 * 自定义接收器
 * 
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";

    public static int sReplyNotifactionId;
    public static int sPrivateMessageNotifactionId;
    public static int sSystemNotifactionId;

    @Override
    public void onReceive(final Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: "
                + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            // send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG,
                    "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            // parseNoticeReceiver(context, bundle);

            // 通知主界面的下面点显示
            noticeTab(context);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");

            JPushInterface.reportNotificationOpened(context,
                    bundle.getString(JPushInterface.EXTRA_MSG_ID));

            // 打开自定义的Activity
            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            try {
                JSONObject jo = new JSONObject(extra);
                String extType = null;
                if (jo.has("ext_type")) {
                    extType = jo.getString("ext_type");
                }
                /** 统一进入小戏中心 */
                if (UserState.getUser() != null) {
                    if (extType != null && extType.equals("index")) {
                        Intent i = new Intent(context, MainActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    } else {// 跳到消息中心
                        Intent i = new Intent(context, MessageCenterActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    }
                } else {// 跳到首页
                    Intent i = new Intent(context, MainActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(i);
                }

                /** 跳到消息中心,不需要设置为已读了 */
                // // 设置为已读
                // if (jo.has("ext_noticeid")) {
                // String ext_noticeid = jo.getString("ext_noticeid");
                // HappyPetApplication.get().getMoccaApi()
                // .noticeClick(ext_noticeid, new IRequest<Boolean>() {
                //
                // @Override
                // public void request(Boolean t) {
                // if (t) {
                // Constants.NoticeLabel.sHasNewMessageNotice = true;
                // } else {
                // Constants.NoticeLabel.sHasNewMessageNotice = false;
                // }
                // context.sendBroadcast(new Intent(
                // Constants.KEY_NOTICE_STATE_CHANGED));
                //
                // context.sendBroadcast(new Intent(
                // Constants.ACTION_RECEIVED_NOTICE));
                //
                // }
                // });
                // }



            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG,
                    "[MyReceiver] 用户收到到RICH PUSH CALLBACK: "
                            + bundle.getString(JPushInterface.EXTRA_EXTRA));
            // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
            // 打开一个网页等..

        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    private void noticeTab(Context context) {

        Constants.NoticeLabel.sHasNewMessageNotice = true;

        Intent notice = new Intent(Constants.KEY_NOTICE_STATE_CHANGED);
        Intent notice2 = new Intent(Constants.ACTION_RECEIVED_NOTICE);
        context.sendBroadcast(notice);
        context.sendBroadcast(notice2);

    }

    private void parseNoticeReceiver(Context context, Bundle bundle) {
        int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);

        int notifyId;

        // 打开自定义的Activity
        String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
        try {
            JSONObject jo = new JSONObject(extra);
            String extType1 = "";
            if (jo.has("ext_type")) {
                extType1 = jo.getString("ext_type");
            }

            if (extType1.equals("index")) {// 跳到首页
                notifyId = sSystemNotifactionId;
                sSystemNotifactionId = notifactionId;
            } else if (extType1.equals("pm")) {// 跳到私信
                notifyId = sPrivateMessageNotifactionId;
                sPrivateMessageNotifactionId = notifactionId;
            } else if (extType1.equals("followfans")) {// 跳到粉丝
                notifyId = sSystemNotifactionId;
                sSystemNotifactionId = notifactionId;
            } else {// 跳到帖子详情页
                notifyId = sReplyNotifactionId;
                sReplyNotifactionId = notifactionId;
            }
            JPushInterface.clearNotificationById(context, notifyId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    public static final String MESSAGE_RECEIVED_ACTION =
            "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    // send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        // if (MainActivity.isForeground) {
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Intent msgIntent = new Intent(MESSAGE_RECEIVED_ACTION);
        msgIntent.putExtra(KEY_MESSAGE, message);
        if (!TextUtils.isEmpty(extras)) {
            try {
                JSONObject extraJson = new JSONObject(extras);
                if (null != extraJson && extraJson.length() > 0) {
                    msgIntent.putExtra(KEY_EXTRAS, extras);
                }
            } catch (JSONException e) {

            }

            // context.sendBroadcast(new Intent(Constants.KEY_RECEIVE_JPUSH_MESSAGE));

        }
        context.sendBroadcast(msgIntent);
        // }
    }
}
